layui.use(['element','zlSelectMultiple', 'table', "layer", 'zlContext', 'zltreemenu','zlTheme', 'upload', 'zlConfig', 'treeGrid', 'zlFormulaCmp'], function (exports) {
    var $ = layui.$,
        zlContext = layui.zlContext,
        zltreemenu = layui.zltreemenu,
        zlTheme = layui.zlTheme,
        layer = layui.layer,
        upload = layui.upload,
        zlConfig = layui.zlConfig,
        statusName = zlConfig.global.result.statusName,
        msgName = zlConfig.global.result.msgName,
        dataName = zlConfig.global.result.dataName,
        OK = zlConfig.global.result.okState,
        form = layui.form,
        zlFormulaCmp = layui.zlFormulaCmp,
        treeGrid = layui.treeGrid,
        zlSelectMultiple = layui.zlSelectMultiple,
        treeGridObj, fullheight = zlContext.setMaxHeihgt(0);

    var tableId = "treeSetting",
        isloadsearch = false,
        loadingLayer = undefined,
        listFileName = new Array;

    function numberInt(value) {
        if (!value) {
            return '只能填写正整数';
        }
        if (value && !/^\d+$/.test(value)) {
            return '只能填写正整数';
        }
    }
    var treeObj = zltreemenu.render('orgtree', {
        dataurl: layui.cache['contentPath'] + "/manager/corefunction/queryorgddata",
        type: "get",
        tableId: tableId,
        isMove: false
    }, {
        onAsyncSuccess: function () {
            gridAction.init();
            layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA);
        },
        onClick: function (event, treeId, treeNode) {
            var winIndex = layer.msg('数据查询中，请稍候...', {
                icon: 16,
                time: false,
                shade: 0.1
            });
            treeGrid.reload(tableId, {
                url: layui.cache['contentPath'] + '/manager/coresysopt/query?ORGID=' + treeNode.RWID,
                height: fullheight,
                done: function (res, curr, count) {
                    layer.close(winIndex)
                    afterloadData(count,this.elem);
                }
            });
        }
    })

    var gridAction = {
        /**switch editor*/
        switchEditor: function (d) {
            return '<input type="checkbox" id="' + d.RWID + '" name="v" value="' + d.v + '" lay-skin="switch" lay-text="启用|关闭" lay-filter="switch_v" ' + (d.v == 1 ? 'checked' : '') + '>';
        },
        /**input editor */
        inputEditor: function (d) {
            var obj = eval('(' + d.XTYPE + ')');
            var defaultValue = obj.value;
            return [, '  <input ' + (obj.datatype ? 'data-type="' + obj.datatype + '"' : '') + ' type="text" id="' + d.RWID + '" name="text_v" autocomplete="off" class="layui-input" lay-filter="text_v" value="' + (d.v ? d.v : defaultValue) + '">'].join('');
        },
        /**combox editor */
        comboxEditor: function (d) {
            var obj = eval('(' + d.XTYPE + ')');
            if (obj.xtype == 'combox') {
                var items = [];
                for (var i = 0; i < obj.items.length; i++) {
                    items.push('<option value="' + obj.items[i].value + '" ' + (d.v == obj.items[i].value ? ' selected ' : '') + '>' + obj.items[i].name + '</option>');
                }
                return [, '<select id="' + d.RWID + '" name="v" lay-filter="combox_v">', items.join(''), '</select>'].join('');
            }
        },
        comboxMultEditor: function (d) {
            var obj = eval('(' + d.XTYPE + ')');
            if (obj.xtype == 'comboxMult') {
                // var items = [];
                // for (var i = 0; i < obj.items.length; i++) {
                //     items.push('<option value="' + obj.items[i].value + '" ' + (d.v == obj.items[i].value ? ' selected ' : '') + '>' + obj.items[i].name + '</option>');
                // }
                var setting =  {};
                setting.showtool = false;
                setting.sourcedata = JSON.stringify(obj.items);
                setting.placeholder = '';
                setting.value = d.v;
                var settingJson  = JSON.stringify(setting) ;
                return ' <h zlcomponent id=' + d.RWID + ' name=\'comboxMultEditor\'  class=\'layui-form-select select-multiple\' settings=\'' + settingJson + '\'></h>';
                // var items = [];
                // for (var i = 0; i < obj.items.length; i++) {
                //     items.push('<option value="' + obj.items[i].value + '" ' + (d.v == obj.items[i].value ? ' selected ' : '') + '>' + obj.items[i].name + '</option>');
                // }
                // return [, '<select id="' + d.RWID + '" name="v" lay-filter="combox_v">', items.join(''), '</select>'].join('');
            }
        },
        /**json editor */
        jsonEditor: function (d) {
            return [
                '<input type="checkbox" name="v" value="' + d.v + '" lay-skin="switch" lay-text="启用|关闭" lay-filter="switch_v" ' + (d.v == 1 ? 'checked' : '') + '>', , '   <input type="text" name="title" autocomplete="off" class="layui-input">'
            ].join('');

        },
        /**group editor */
        groupEditor: function (d) {
            return '<div></div>';
        },
        /**interface editor */
        interfaceEditor: function (d) {
            var obj = eval('(' + d.XTYPE + ')');
            if (obj.xtype == 'interface') {
                var param = {
                    'fullInterfaceName': obj.interfaceName
                }
                var items = [];
                zlContext.asyncGet(layui.cache['contentPath'] + '/core/common/getinterfaceimplclass', param, function (result) {
                    if (result[statusName] == OK) {
                        var datas = result[dataName];
                        // var $select = $('#' + d.RWID);
                        for (var i = 0; i < datas.length; i++) {
                            items.push('<option value="' + datas[i].name + '" ' + (d.v == datas[i].name ? ' selected ' : '') + '>' + datas[i].desc + '</option>');
                        }
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                }, false);
                return [
                    '<select id="' + d.RWID + '" name="v" lay-filter="combox_v">', '   <option value="none" ' + (d.v == "none" ? ' selected ' : '') + '>无</option>', items.join(''), '</select>'
                ].join('');
            }
        },
        fileUploadEditor: function (d) {
            var obj = eval('(' + d.XTYPE + ')');
            var filetype = obj.filetype || "";
            var multiple = obj.multiple || false;
            var count = obj.count || 1;
            var html = "";
            var accept = "file";
            var classname = "sysoptFileUpload";
            $.extend(obj, {
                filter: 'none'
            });
            //图片类型
            if ("img" == filetype) {
                accept = "image/*";
                $.extend(obj, {
                    filter: ", acceptMime:\'image/jpg,image/png\', exts: \'jpg|png|bmp|jpeg|gif\'"
                });
                if (count == 1) {
                    html = '<img class="layui-logo-img" atl src="' + layui.cache['contentPath'] + d.v + '">';
                } else {
                    classname = "sysoptMFileUpload";
                    var v = new Array;
                    if (d.v) {
                        v = eval('(' + d.v + ')');
                    }
                    for (var i = 1; i <= count; i++) {
                        if (v.length >= i - 1 && v[i - 1] && v instanceof Array) {
                            html += '<img class="layui-logo-img" atl src="' + layui.cache['contentPath'] + v[i - 1] + '">';
                        } else {
                            html += '<img class="layui-logo-img" atl src="' + layui.cache['contentPath'] + '/static/image/errorload.gif">';
                        }
                    }
                }
            }

            return [
                html, '<button id="' + d.RWID + '" class="layui-btn layui-btn-xs ' + classname + '" lay-data="{size:1024,number:' + count + ',multiple:' + multiple + ',accept:\'' + accept + '\',url: \'' + layui.cache['contentPath'] + obj.url +
                '\'' + ('none' == obj.filter ? '' : obj.filter) + '}">&nbsp;上传&nbsp;</button>'
            ].join('');
        },
        formEditor: function (d) {
            var obj = eval('(' + d.XTYPE + ')'),
                v = d.V,
                html = "",
                opdtid = d.RWID,
                value = obj.value == 'XTYPE_C' ? obj.value : JSON.stringify(obj.value);
            if (v) {
                v = eval('(' + v + ')');
                html += '<span>' + v.theme_title + '</span>';
            }
            html += '<button id="' + d.RWID + '" class="layui-btn layui-btn-xs" lay-event="formbtn" lay-data="' + value + '" lay-optid="' + opdtid + '">&nbsp;设置&nbsp;</button>';
            return html;
        },
        //文本域编辑
        textareaEditor: function(d){
            var obj = eval('(' + d.XTYPE + ')'),
                optid = d.RWID,
                value = obj.value == 'XTYPE_CV' ? obj.value : JSON.stringify(obj.value);
            return '<button title="'+d.TITLE+'" id="' + d.RWID + '" class="layui-btn layui-btn-xs" lay-event="textarea-btn" lay-data="' + value + '" lay-optid="' + optid + '">&nbsp;编辑脚本&nbsp;</button>'
        },
        //通用按钮点击
        commonBtnEditor: function(d){
            var obj = eval('(' + d.XTYPE + ')'),
                optid = d.RWID,
                value = d.v;
            return '<button id="' + d.RWID + '" class="layui-btn layui-btn-xs" lay-event="common-btn-click" lay-data="' + value + '" lay-optid="' + optid + '">&nbsp;设置&nbsp;</button>'
        },
        /**
         * 编辑构建编辑器
         */
        buildEditor: function (d) {
            var obj = eval('(' + d.XTYPE + ')');
            if (obj.xtype === "switch") {
                return this.switchEditor(d);
            } else if (obj.xtype === "group") {
                return this.groupEditor(d);
            } else if (obj.xtype === "input") {
                return this.inputEditor(d);
            } else if (obj.xtype === "combox") {
                return this.comboxEditor(d);
            }else if (obj.xtype === "comboxMult") {
                return this.comboxMultEditor(d);
            } else if (obj.xtype === "json") {
                return this.jsonEditor(d);
            } else if (obj.xtype == 'interface') {
                return this.interfaceEditor(d);
            } else if (obj.xtype == 'btnFileUpload') {
                return this.fileUploadEditor(d);
            } else if (obj.xtype == 'form') {
                return this.formEditor(d);
            } else if (obj.xtype == 'textarea'){
                return this.textareaEditor(d);
            } else if (obj.xtype == 'commonBtn'){
                return this.commonBtnEditor(d);
            }
        },
        init: function () {
            var nodes = treeObj.getNodes();
            if (nodes.length > 0) {
                treeObj.selectNode(nodes[0]);
            }
            //var treeNode=nodes[0];
            //var index = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });


            treeGridObj = treeGrid.render({
                id: tableId,
                elem: '#' + tableId,
                method: 'post',
                treeId: 'RWID', //树形id字段名称
                treeUpId: 'SYS_PARENTID', //树形父id字段名称
                treeShowName: 'TITLE', //以树形式显示的字段
                sortload: false,
                limit: 1000,
                height: fullheight,
                isOpenDefault: false,
                chkboxType: {
                    "Y": "",
                    "N": ""
                }, //父子节点的关联关系 默认值：{ "Y": "ps", "N": "ps" }
                cols: [
                    [{
                        field: 'TITLE',
                        width: '400',
                        title: '描述'
                    }, {
                        field: 'BEIZ',
                        width: '400',
                        title: '备注'
                    }, {
                        field: 'v',
                        width: '350',
                        title: '选项值',
                        templet: this.buildEditor.bind(this)
                    }]
                ],
                isPage: false,
                response: zlConfig.global.gridResponse,
                done: function (res, curr, count) {
                    layer.close(index);
                    afterloadData(count,this.elem);
                }
            });
        },
        modify: function (id, obj) {
            var row = treeGrid.cache[tableId].data.map[id];
            var param = {
                RWID: row.RWID,
                v: obj.value,
                k: row.k,
                ORGID: row.ORGID,
                SYS_SORT: row.SYS_SORT,
                TITLE:row.TITLE
            }
            param.v = obj.value;
            zlContext.post(layui.cache['contentPath'] + '/manager/coresysopt/modify', param, function (result) {
                if (result[statusName] == OK) {
                    return true;
                } else {
                    zlContext.errorMsg(result[msgName]);
                }
            });
        },
        search: function () {
            var param = {}
            if ($('#edtSeacherValue').val() !== '') {
                param['KEYVALUE'] = '%' + $('#edtSeacherValue').val() + '%';
                isloadsearch = true;
            }
            layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
        },
        editTextareaGrid: function(title,rwid, orgid, textareaData, url) {
            var textareaFrm = [
                  '<div class="layui-tab-content" style="height:375px">'
                , '     <div zl-action="formula" name="formula" zlcomponent class="zl-formulacmp"></div>'
                , '     <div style="height: 30px;"><span>填写首页定义选择脚本</span>'
                , '         <button class="layui-btn layui-btn-sm custom-formula-btn" type="button" style="float:right;height: 25px;line-height: 25px;">自定义</button>'
                , '     </div>'
                , '     <div class="tableace"><div id="textarea-editor" placeholder="请输入" style="height:397px; border:1px solid #ddd"></div></div>'
                , '</div>'
            ];
            layer.open({
                type: 1
                , id: 'frmTextareaLayer'
                , title: "编辑"
                , area: ['850px', '540px']
                , content: textareaFrm.join('')
                , btn: ['确定', '取消']
                , success: function () {
                    ace.require("ace/ext/language_tools");
                    var aceEditor = ace.edit("textarea-editor");
                    aceEditor.setOptions({
                        enableBasicAutocompletion: true,
                        enableSnippets: true,
                        enableLiveAutocompletion: true,//只能补全
                    });
                    aceEditor.setTheme("ace/theme/monokai");//monokai模式是自动显示补全提示
                    aceEditor.getSession().setMode("ace/mode/groovy");//语言
                    aceEditor.getSession().setTabSize(4);
                    aceEditor.setFontSize(14);
                    if(textareaData){
                        aceEditor.setValue(textareaData);
                    }
                }
                , yes: function (index, layero) {
                    var aceEditor = ace.edit("textarea-editor");
                    var text = aceEditor.getValue();
                    var params = {
                        'RWID': rwid,
                        'ORGID': orgid,
                        'XTYPE_CV': text,
                        'TITLE':title
                    }
                    zlContext.post(url, params, function (data) {
                        if (data.state == 'OK') {
                            zlContext.successMsg('保存成功');
                            layer.close(index);
                        } else {
                            zlContext.errormsg(data[msgName]);
                        }
                    });
                    return false;
                }
            })
        }
    };
    form.on('switch(switch_v)', function (obj) {
        obj.value = obj.elem.checked ? 1 : 0;
        gridAction.modify(obj.elem.id, obj);
    });
    form.on('select(combox_v)', function (obj) {
        gridAction.modify(obj.elem.id, obj);
    });
    treeGrid.on('tool(treeSetting)', function (obj) {
        var layEvent = obj.event;
        var data = $(this).attr("lay-data");
        var optid = $(this).attr("lay-optid");
        if (layEvent == "formbtn") {
            var v = obj.data.v;
            var currNodeRwid = '9C876276D8884BFF94DF343E2A4EED7D';
            if (data == 'XTYPE_C') {
                var nodes = treeObj.getSelectedNodes();
                if (nodes.length > 0) {
                    currNodeRwid = nodes[0].RWID;
                }
                var params = {},
                    allData = [];
                params.orgid = currNodeRwid;
                params.optid = optid;
                zlContext.asyncGet(layui.cache['contentPath'] + '/manager/coresysopt/queryxtypec', params, function (data) {
                    if (data.state == 'OK') {
                        allData = eval('(' + data.obj + ')');
                    } else {
                        allData = zlTheme.defaulTheme;
                    }

                    zlTheme.showform(allData, currNodeRwid, optid, v);
                });
            }
        }else if(layEvent == 'textarea-btn'){;
            var title = $(this).attr("title");
            var curNodeOrgid = '9C876276D8884BFF94DF343E2A4EED7D';
            if (data == 'XTYPE_CV') {
                var nodes = treeObj.getSelectedNodes();
                if (nodes.length > 0) {
                    curNodeOrgid = nodes[0].RWID;
                }
                var params = {
                    'orgid': curNodeOrgid,
                    'optid': optid
                },
                saveUrl = layui.cache['contentPath'] + '/manager/coresysopt/modify';
                zlContext.asyncGet(layui.cache['contentPath'] + '/manager/coresysopt/queryxtypec', params, function (data) {
                    if (data.state == 'OK') {
                        gridAction.editTextareaGrid(title,optid, curNodeOrgid, data.obj, saveUrl);
                    } else {
                       zlContext.errorMsg(data[msgName]);
                    }
                });
            }
        }else if(layEvent == 'common-btn-click'){
            commonBtnAction.currentEditObj = obj;
            var d = obj.data;
            var map = eval('(' + d.XTYPE + ')');
            if(map && map['methodName']){
                var methodName = map['methodName'];
                if(methodName && commonBtnAction[methodName] instanceof Function){
                    commonBtnAction[methodName].call(this, d);
                }else{
                    zlContext.warnMsg('未定义按钮响应事件');
                }
            }else{
                zlContext.warnMsg('未定义按钮响应事件');
            }
        }
    });

    //通用按钮事件
    var commonBtnAction = {
        currentEditObj: undefined,
        wechatConfig: function(data){
            loadingLayer = layer.msg('数据加载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
            var errorFlag = false;
            var param = {
                'orgid': data['ORGID'],
                'optid': data['RWID']
            };
            var v = {
                'enabled': '0',
                'appId': '',
                'appSecret': '',
                'callbackDomain': '',
                'interfaceImplClass': 'none'
            };
            zlContext.asyncGet(layui.cache['contentPath'] + '/manager/coresysopt/queryxtypec', param, function (result) {
                if (result[statusName] == OK) {
                    if(result[dataName] != "" && result[dataName] != undefined){
                        v = eval('(' + result[dataName] + ')');
                    }
                } else {
                   zlContext.errorMsg(result[msgName]);
                   errorFlag = true;
                   return;
                }
            });
            if(errorFlag){
                layer.close(loadingLayer);
                return;
            }

            var map = eval('(' + data.XTYPE + ')');
            param = {
                'fullInterfaceName': map['interfaceName']
            }
            var items = [];
            zlContext.asyncGet(layui.cache['contentPath'] + '/core/common/getinterfaceimplclass', param, function (result) {
                if (result[statusName] == OK) {
                    var datas = result[dataName];
                    // var $select = $('#' + d.RWID);
                    items.push('<option value="none" ' + (v['interfaceImplClass'] == "none" ? ' selected ' : '') + '>无</option>');
                    for (var i = 0; i < datas.length; i++) {
                        items.push('<option value="' + datas[i].name + '" ' + (v['interfaceImplClass'] == datas[i].name ? ' selected ' : '') + '>' + datas[i].desc + '</option>');
                    }
                } else {
                    zlContext.errorMsg(result[msgName]);
                    errorFlag = true;
                    return;
                }
            }, false);

            if(errorFlag){
                layer.close(loadingLayer);
                return;
            }
            
            var frmConfigLayer = [
                '<div style="padding-top: 20px;padding-right: 20px;">'
                , '<form id ="frmWechatConfig" class="layui-form" action="" lay-filter="frmWechatConfig" style="height: 330px;">'
				, '	<div class="layui-form-item layui-hide">'
				, '		<div class="layui-input-block">'
                , '			<input type="text" name="RWID" class="layui-input" value="' + data['RWID'] + '">'
                , '			<input type="text" name="ORGID" class="layui-input" value="' + data['ORGID'] + '">'
				, '		</div>'
                , '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">微信扫码登录：</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="checkbox" name="enabled" lay-verify="required" valueformat="1|0" value="' + v['enabled'] + '" lay-skin="switch" lay-text="启用|关闭" ' + (v['enabled'] == '1' ? 'checked' : '') + '>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">APPID：</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="appId" value="' + v['appId'] + '" maxlength="64" lay-verify="required" placeholder="请输入APPID"  class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">AppSecret：</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="password" name="appSecret" value="' + v[''] + '" maxlength="64" lay-verify="required" placeholder="请输入AppSecret"  class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">微信回调域：</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" maxlength="128" name="callbackDomain" value="' + v[''] + '" lay-verify="required" placeholder="例如：http://www.sample.com"  class="layui-input"> '
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">绑定用户验证码短信平台：</label>'
				, '		<div class="layui-input-block">'
                , '		    <select name="interfaceImplClass" lay-verify="required"> ' + items.join('') + '</select>'
                , '		</div>'
				, '	</div>  '
				, '	<div class="layui-form-item" style="margin-top: 30px;">'
				, '		<div class="layui-input-block">'
				, '		  <button class="layui-btn" lay-submit lay-filter="frmWechatConfig">保存</button>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
            ]
            layer.open({
                type: 1,
				title: "微信扫码登录配置",
				id: 'frmWechatConfigLayer',
				area: ['600px','393px'],
				content: frmConfigLayer.join(''),
				success: function (layero, index) {
                    zlContext.autoFill($('#frmWechatConfig'), v);
                    form.render(null, 'frmWechatConfig');
                    layer.close(loadingLayer);
                    loadingLayer = index;
                }
            });
        }
    };

    var formulaCallback = {
        callbackFormula: function(param){
            var editorVal = param['MODELE_VALUE'];
            var aceEditor = ace.edit("textarea-editor");
            aceEditor.setValue(editorVal);
            layer.close(param.addformulaPop);
        }
    };

    $("body").on('click', '#frmTextareaLayer .custom-formula-btn', function(){
        var aceEditor = ace.edit("textarea-editor");
        var text = aceEditor.getValue();
        var formulaSettings = "{'dataurl':'"+layui.cache['contentPath'] + "/manager/coremodeldesign/queryFormulaDesc','method':'post','isordinary':false}";
        zlFormulaCmp.render($('[zl-action="formula"]'),text,formulaSettings,formulaCallback);
    });

    // 搜索事件
    $('#btnSeacher').on('click', function () {
        gridAction.search();
    });
    $('#edtSeacherValue').on('keyup', function (event) {
        var keyCode = event.keyCode;
        if (keyCode == 13) {
            gridAction.search();
        }
        if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
            $('#btnSeacher').trigger('click');
            isloadsearch = false;
        }
    });

    //监听刷新的事件
    layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
        var nodes = treeObj.getSelectedNodes();
        var currNodeRwid;
        if (nodes.length > 0) {
            currNodeRwid = nodes[0].RWID;
        } else {
            treeGrid.delRow(tableId, treeGrid.cache[tableId].data.list);
            return;
        }
        var index = layer.msg('数据查询中，请稍候...', {
            icon: 16,
            time: 2000000,
            shade: 0.1
        });
        var loadGridData = function (id, url, param) {
            treeGridObj.reload({
                url: url,
                method: 'post',
                where: param,
                done: function (res, curr, count) {
                    layer.close(index);
                    afterloadData(count,this.elem);
                }
            }, true);
        }
        loadGridData('treeSetting', layui.cache['contentPath'] + '/manager/coresysopt/query?ORGID=' + currNodeRwid, param);
    });

    layui.onevent('zlSelectMultiple', 'div(comboxMultEditor)', function (params) {
        var elem = params.elem,
            rwid = $(elem).attr('id'),
            v = params.value.join(',');
        gridAction.modify(rwid, { 'value': v });
    });

    //提交
	form.on('submit(frmWechatConfig)', function (frm) {
        var row = commonBtnAction.currentEditObj.data;
        var field = frm.field;
        var v = {
            'enabled': field['enabled'],
            'appId': field['appId'],
            'appSecret': field['appSecret'],
            'callbackDomain': field['callbackDomain'],
            'interfaceImplClass': field['interfaceImplClass']
        }
		var param = {
            'RWID': row.RWID,
            'v': field['enabled'],
            'k': row.k,
            'ORGID': row.ORGID,
            'SYS_SORT': row.SYS_SORT,
            'XTYPE_CV': JSON.stringify(v),
            'TITLE':row.TITLE
        }
        param.v = field['enabled'];
        zlContext.post(layui.cache['contentPath'] + '/manager/coresysopt/modify', param, function (result) {
            if (result[statusName] == OK) {
                commonBtnAction.currentEditObj.data['v'] = param['v'];
                commonBtnAction.currentEditObj.data['XTYPE_CV'] = param['XTYPE_CV'];
                layer.close(loadingLayer);
                return true;
            } else {
                zlContext.errorMsg(result[msgName]);
                return false;
            }
        });
        return false;
	});

    $(window).on('resize', function () {
        zlContext.setMaxHeihgt(0);
    }).resize();
    // 文件上传
    function fileUpload() {
        // 单文件和多文件需要分开渲染，一起会有问题，单文件
        upload.render({
            elem: '.sysoptFileUpload',
            done: function (res, index, upload) {
                if (res[statusName] != OK) {
                    return zlContext.errorMsg(res[msgName]);
                } else {
                    var $item = $(this.item);
                    gridAction.modify($item.attr("id"), res[dataName]);
                    $item.prev("img").attr("src", layui.cache['contentPath'] + res[dataName].value);
                }
            },
            error: function () {
                zlContext.errorMsg('上传失败');
            }
        });
        upload.render({
            elem: '.sysoptMFileUpload',
            before: function (obj) {
                //清空上传文件之前清空
                listFileName.length = 0;
            },
            done: function (res, index, upload) {
                if (res[statusName] != OK) {
                    return zlContext.errorMsg(res[msgName]);
                } else {
                    listFileName.push(res[dataName].value);
                }
            },
            // 全部上传完成
            allDone: function (obj) {
                var $item = $(this.item),
                    imgItems = $item.prevAll('img'),
                    length = imgItems.length;
                $.each(listFileName, function (index, value) {
                    $(imgItems[length - 1]).attr("src", layui.cache['contentPath'] + value);
                    length--;
                });
                for (var i = length - 1; i >= 0; i--) {
                    $(imgItems[i]).attr("src", layui.cache['contentPath'] + "/static/image/errorload.gif");
                }
                // 少于4个的时候，把原来的存进去
                // if(listFileName.length<4){
                //     listFileName.length==0;
                //   for(var i=length-1; i>=0;i--){
                //     var src = $(imgItems[i]).attr("src");
                //     if(src){
                //         listFileName.push(src. replace(layui.cache['contentPath'],""));   
                //     }
                //   }  

                // }
                var param = {};
                param.value = JSON.stringify(listFileName);
                gridAction.modify($item.attr("id"), param);
            },
            error: function () {
                zlContext.errorMsg('上传失败');
                $('.selectMulti').next().width($('.selectMulti').width());
            }
        });
        $("img.layui-logo-img").click(function () {
            layer.open({
                type: 1,
                title: false,
                shadeClose: true,
                content: '<img class="layui-logo-img-big" src="' + $(this).attr('src') + '" />'
            });
        });
    }
    function afterloadData(count,elem){
        count || elem.next('.layui-table-view').find('.layui-table-header').css('overflow', 'auto');
        layui.each($('select'), function (index, item) {
            var curelem = $(item);
            curelem.val(curelem.data('value')).parents('div.layui-table-cell').css({
                'overflow': 'visible'
            });
            curelem.val(curelem.data('value')).parents('div.layui-table-cell').addClass('layui-table-cell-active');
        });
        layui.each($('.select-multiple'), function (index, item) {
            var curelem = $(item);
            curelem.parents('tr').height('70px');
            curelem.find('.selectMulti').css({'height':'60px','top':'-15px'});
            curelem.val(curelem.data('value')).parents('div.layui-table-cell').css('overflow', 'visible');
            curelem.val(curelem.data('value')).parents('div.layui-table-cell').addClass('layui-table-cell-active');
        });
        $("input[name='text_v']").change(function (e) {
            var datatype = $(this).attr("data-type");
            if (datatype) {
                if (typeof (eval(datatype)) == "function") {
                    var value = $(this).val();
                    var msg = eval(datatype + '("' + value + '");');
                    if (msg) {
                        layer.msg(msg, {
                            icon: 5,
                            shift: 6
                        });
                        $(this).focus();
                        return;
                    }
                }
            }
            $(this).css("background-color", "#FFFFCC");
            gridAction.modify(e.target.id, e.target);
        });
        //文件上传
        fileUpload();
    }
});